import ListEmpty from '@/components/antd-comp/empty'
import { showMessage } from '@/components/antd-comp/message'
import TableGrid from '@/components/antd-comp/table'
import { columnsProps } from '@/components/antd-comp/table/constants'
import ThemeBtn from '@/components/antd-comp/theme-btn'
import FouterPage from '@/components/fouter-page'
import InputAntDef from '@/components/input/InputAntDef'
import { useRouteStoreHook } from '@/store/routeStore'
import { useBuriedEvent } from '@/util/buried'
import { ExclamationCircleFilled } from '@ant-design/icons'
import { Modal } from 'antd'
import { useContext, useState,useRef } from 'react'
import { useTranslation } from 'react-i18next'
import { userContext } from '../../../contexts/userContext'
import { getUsersApi } from '../../../controllers/API/user'
import { captureAndAlertRequestErrorHoc } from '../../../controllers/request'
import { useTable } from '../../../util/hook'
import { UserDel } from '../API'
import UserEditDia from './UserEditDia'
import UserPassWordEditDia from './UserPassWordEditDia'
import UserRoleModal from './UserRoleModal'
import './style/index.less'

// table的唯一id
const getUniqueKey = (record: any) => record.user_id
const { confirm } = Modal

export default function Users(params) {
  useRouteStoreHook(['成员管理'])
  const { user } = useContext(userContext)
  const { t } = useTranslation()
  const { UserBuriedEvent } = useBuriedEvent()
  const tableRef = useRef(null);

  const {
    page,
    pageSize,
    data: datalist,
    total,
    loading,
    setPage,
    search,
    reload
  } = useTable({ pageSize: 10 }, param => {
    // 重置表格滚动位置
    if (tableRef.current) {
      const tableBody = tableRef.current.getElementsByClassName('ant-table-body')[0];
      if (tableBody) {
        tableBody.scrollTop = 0;
      }
    }
    return getUsersApi(param.keyword, param.page, param.pageSize);
  })

  // 编辑
  const [roleOpenId, setRoleOpenId] = useState(null)
  const handleRoleChange = () => {
    setRoleOpenId(null)
    reload()
  }
  /* 弹窗 */
  const [open, setOpen] = useState(false)
  const [obj, setObj] = useState(null)
  const [openInfo, setOpenInfo] = useState(false)
  const [objInfo, setObjInfo] = useState(null)

  const handleDeleteFun = id => {
    UserBuriedEvent({
      event_name: '【删除】用户管理按钮',
      data_id: id || null
    })
    // 删除权限限制
    // if (!hasFuncPermission([Func.prompt.del])) {
    //   return
    // }
    confirm({
      title: t('prompt'),
      icon: <ExclamationCircleFilled style={{ color: 'red' }} />,
      content: '确认删除该用户?',
      okText: t('delete'),
      okType: 'danger',
      cancelText: t('cancel'),
      autoFocusButton: null,
      centered: true,
      destroyOnClose: true,
      onOk() {
        captureAndAlertRequestErrorHoc(
          UserDel({ user_id: id })
            .then(res => {
              UserBuriedEvent({
                page: '用户管理页面',
                event_name: '确定【删除】用户管理按钮',
                data_id: id || null,
                detail: JSON.stringify({ 结果: '成功' })
              })
              reload()
              showMessage({
                content: '删除成功',
                type: 'success'
              })
            })
            .catch(() => {
              UserBuriedEvent({
                page: '用户管理页面',
                event_name: '确定【删除】用户管理按钮',
                data_id: id || null,
                detail: JSON.stringify({ 结果: '失败' })
              })
            })
        )
      }
    })
  }

  // 定义tableColumns
  const tableColumns: columnsProps[] = [
    {
      dataIndex: 'user_name',
      title: t('system.username'),
      width: 140,
      render: (text, _record, _index) => text || '--'
    },
    {
      dataIndex: 'create_time',
      title: t('createTime'),
      width: 180,
      render: (text, _record, _index) => text?.replace('T', ' ')
    },
    {
      dataIndex: 'operation',
      title: t('operations'),
      fixed: 'right',
      width: 160,
      render: (_text, record, _index) => (
        <div className="ml-[-16px] bg-inherit">
          {/* <span
            onClick={() => {
              setObjInfo({
                // firm: record.firm,
                // code: record.code,
                user_name: record.user_name,
                id: record.user_id
              })
              setOpenInfo(true)
            }}
            className="tableSettingName ml-[16px] px-0 text-[#062FF8]"
          >
            {t('edit')}
          </span> */}
          <span
            onClick={() => {
              setObj({
                name: record.user_name,
                id: record.user_id,
                password_repeat: '',
                password: ''
              })
              setOpen(true)
            }}
            className="tableSettingName ml-[16px] px-0 text-[#062FF8]"
          >
            密码重置
          </span>
          {/* user.user_id !== record.user_id */}
          <span onClick={() => handleDeleteFun(record.user_id)} className="tableSettingName ml-[16px] px-0 text-[red]">
            删除
          </span>
          {/* 为了实现右侧fix时border-radius额外增加的遮罩层 */}
          <div className="common-table-right-fixed-layer2">{''}</div>
          <div className="common-table-right-fixed-layer3">{''}</div>
        </div>
      )
    }
  ]

  return (
    <div className="user-manager-container relative h-full min-w-[600px] bg-[#f5f7fb]">
      {loading && (
        <div className="absolute left-0 top-0 z-10 flex h-full w-full items-center justify-center bg-[rgba(255,255,255,0.6)] dark:bg-blur-shared">
          <span className="loading loading-infinity loading-lg"></span>
        </div>
      )}
      <div className="absolute left-0 top-0 m-[32px] rounded-[6px] bg-[#ffffff]">
        <div className="flexRowJustBet flex py-[24px] pl-[24px] pr-[32px]">
          <div className="flexRowStart">
            <InputAntDef
              name="UsersListSearch"
              autoComplete="off"
              searchFun={e => search(e.target.value)}
              placeholder={t('system.username')}
            ></InputAntDef>
          </div>
          <ThemeBtn
            className="themeBtn_callwordPage migu-font-600 h-[36px] w-[92px]"
            onClick={() => {
              setObjInfo({})
              setOpenInfo(true)
            }}
          >
            {t('create')}
          </ThemeBtn>
        </div>

        <div className="relative top-[0] max-h-[calc(100vh-180px)] overflow-y-scroll px-[24px] scrollbar-hide">
          <TableGrid
            tableInfo={{
              tableData: datalist,
              tableColumns,
              getUniqueKey,
              scrollHeight: 'calc(100vh - 180px)',
              scrollWidth: 500,
            }}
            emptyComponent={
              !loading && !datalist?.length ? (
                <ListEmpty style={{ height: 'calc(100vh - 314px)', margin: 0 }} />
              ) : (
                <div style={{ height: 'calc(100vh - 314px)', background: '#ffffff', margin: 0 }}></div>
              )
            }
          />
        </div>
        {/* fouter */}
        <FouterPage
          className="sys-footer-common-bottom-box sys-footer-common-gray-text rounded-[6px]"
          style={{ background: '#FFFFFF' }}
          page={page}
          pageSize={pageSize}
          total={total}
          setPage={newPage => setPage(newPage)}
        ></FouterPage>
      </div>
      <UserRoleModal id={roleOpenId} onClose={() => setRoleOpenId(null)} onChange={handleRoleChange}></UserRoleModal>
      {/* 密码弹窗 */}
      {open ? (
        <UserPassWordEditDia
          submitData={() => {
            reload()
          }}
          open={open}
          setOpen={setOpen}
          obj={obj}
        ></UserPassWordEditDia>
      ) : null}
      {/* 编辑弹窗 */}
      {openInfo ? (
        <UserEditDia
          submitData={() => {
            reload()
          }}
          open={openInfo}
          setOpen={setOpenInfo}
          obj={objInfo}
        ></UserEditDia>
      ) : null}
    </div>
  )
}
